package com.fin.quant.domain.repository.impl;

import com.fin.quant.common.TargetType;
import com.fin.quant.domain.entity.TagEntity;
import com.fin.quant.domain.repository.TagRepository;
import com.fin.quant.domain.repository.TargetTagRepository;
import com.fin.quant.instra.mysql.mapper.TargetTagMapper;
import com.fin.quant.instra.mysql.model.TargetTag;
import com.fin.quant.instra.mysql.model.TargetTagExample;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 目标标签关系仓储实现
 */
@Service
@Slf4j
public class TargetTagRepositoryImpl implements TargetTagRepository {

    @Autowired
    private TargetTagMapper targetTagMapper;

    @Autowired
    private TagRepository tagRepository;

    @Override
    public Map<Long, List<TagEntity>> getAssetTagsMap(List<Long> assetIdList) {
        if (CollectionUtils.isEmpty(assetIdList)) {
            return Collections.emptyMap();
        }

        try {
            // 查询目标标签关系
            TargetTagExample example = new TargetTagExample();
            example.createCriteria().andTargetIdIn(assetIdList)
                    .andTargetTypeEqualTo(TargetType.asset.getType());
            List<TargetTag> targetTags = targetTagMapper.selectByExample(example);

            if (CollectionUtils.isEmpty(targetTags)) {
                return Collections.emptyMap();
            }

            // 提取所有标签ID
            List<Long> tagIds = targetTags.stream()
                    .map(TargetTag::getTagId)
                    .distinct()
                    .collect(Collectors.toList());

            // 批量查询标签信息
            Map<Long, TagEntity> tagMap = tagRepository.getTagsMap(tagIds);

            // 按目标ID分组标签
            Map<Long, List<TagEntity>> map = targetTags.stream()
                    .collect(Collectors.groupingBy(
                            TargetTag::getTargetId,
                            Collectors.mapping(
                                    targetTag -> tagMap.get(targetTag.getTagId()),
                                    Collectors.toList())));

            return map;
        } catch (Exception e) {
            log.error("获取资产标签映射失败, targetIdList: {}", assetIdList, e);
            return Collections.emptyMap();
        }
    }
}
